<template>
  <div class="profile-view">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-container">
        <div class="nav-brand">
          <h2>电影推荐系统</h2>
        </div>
        
        <div class="nav-menu">
          <router-link to="/" class="nav-link">
            首页
          </router-link>
          <router-link to="/movies" class="nav-link">
            电影库
          </router-link>
          <router-link to="/recommendations" class="nav-link">
            推荐
          </router-link>
          <router-link to="/profile" class="nav-link" active-class="active">
            个人中心
          </router-link>
        </div>
        
        <div class="nav-user">
          <span class="user-name">{{ authStore.user?.username }}</span>
          <button @click="handleLogout" class="logout-btn">
            退出
          </button>
        </div>
      </div>
    </nav>
    
    <!-- 主要内容 -->
    <main class="main-content">
      <!-- 用户信息卡片 -->
      <div class="user-info-card">
        <div class="user-avatar">
          <div class="avatar-circle">
            {{ userInitials }}
          </div>
        </div>
        
        <div class="user-details">
          <h1 class="user-name-title">{{ fullName || authStore.user?.username }}</h1>
          <p class="user-email">{{ authStore.user?.email }}</p>
          <p class="user-username">@{{ authStore.user?.username }}</p>
        </div>
      </div>
      
      <!-- 统计信息 -->
      <div v-if="moviesStore.userStats" class="stats-section">
        <h2>我的统计</h2>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon">🎬</div>
            <div class="stat-content">
              <h3>{{ moviesStore.userStats.total_ratings }}</h3>
              <p>已评分电影</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">⭐</div>
            <div class="stat-content">
              <h3>{{ moviesStore.userStats.average_rating.toFixed(1) }}</h3>
              <p>平均评分</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">🎭</div>
            <div class="stat-content">
              <h3>{{ moviesStore.userStats.favorite_genres.length }}</h3>
              <p>喜爱类型</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 喜爱的电影类型 -->
      <div v-if="moviesStore.userStats?.favorite_genres.length > 0" class="favorite-genres-section">
        <h2>喜爱的电影类型</h2>
        <div class="genres-chart">
          <div
            v-for="genre in moviesStore.userStats.favorite_genres"
            :key="genre.name"
            class="genre-bar"
          >
            <div class="genre-info">
              <span class="genre-name">{{ genre.name }}</span>
              <span class="genre-count">{{ genre.count }} 部</span>
            </div>
            <div class="genre-progress">
              <div
                class="genre-progress-bar"
                :style="{ width: getGenrePercentage(genre.count) + '%' }"
              ></div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 最近评分 -->
      <div class="recent-ratings-section">
        <div class="section-header">
          <h2>最近评分</h2>
          <button @click="refreshRatings" class="refresh-btn">
            刷新
          </button>
        </div>
        
        <div v-if="ratingsStore.isLoading" class="loading">
          <div class="loading-spinner"></div>
          <p>正在加载评分...</p>
        </div>
        
        <div v-else-if="recentRatings.length > 0" class="ratings-list">
          <div
            v-for="rating in recentRatings"
            :key="rating.id"
            class="rating-item"
            @click="goToMovie(rating.movie)"
          >
            <div class="rating-movie-info">
              <h3 class="rating-movie-title">{{ rating.movie_title }}</h3>
              <p class="rating-timestamp">{{ formatDate(rating.timestamp) }}</p>
            </div>
            
            <div class="rating-score">
              <div class="stars">
                <span
                  v-for="i in 5"
                  :key="i"
                  class="star"
                  :class="{ filled: i <= rating.rating }"
                >
                  ★
                </span>
              </div>
              <span class="rating-number">{{ rating.rating }}/5</span>
            </div>
          </div>
        </div>
        
        <div v-else class="no-ratings">
          <p>您还没有评分任何电影</p>
          <router-link to="/movies" class="browse-movies-btn">
            去评分电影
          </router-link>
        </div>
      </div>
      
      <!-- 评分分布 -->
      <div v-if="ratingDistribution.length > 0" class="rating-distribution-section">
        <h2>评分分布</h2>
        <div class="distribution-chart">
          <div
            v-for="dist in ratingDistribution"
            :key="dist.rating"
            class="distribution-bar"
          >
            <div class="distribution-info">
              <span class="distribution-rating">{{ dist.rating }} 星</span>
              <span class="distribution-count">{{ dist.count }} 部</span>
            </div>
            <div class="distribution-progress">
              <div
                class="distribution-progress-bar"
                :style="{ width: getDistributionPercentage(dist.count) + '%' }"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 我的留言 -->
      <div class="user-comments-section">
        <div class="section-header">
          <h2>我的留言</h2>
          <button @click="refreshComments" class="refresh-btn">
            刷新
          </button>
        </div>
        
        <div v-if="isLoadingComments" class="loading">
          <div class="loading-spinner"></div>
          <p>正在加载留言...</p>
        </div>
        
        <div v-else-if="userComments.length > 0" class="comments-list">
          <div
            v-for="comment in userComments"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-header">
              <h3 class="movie-title" @click="goToMovie(comment.movie)">{{ comment.movie_title }}</h3>
              <span class="comment-date">{{ formatDate(comment.timestamp) }}</span>
            </div>
            
            <div class="comment-content">
              <p>{{ comment.content }}</p>
            </div>
            
            <div class="comment-actions">
              <button 
                @click="goToMovie(comment.movie)" 
                class="view-movie-btn"
              >
                查看电影
              </button>
              <button 
                @click="editComment(comment)" 
                class="edit-comment-btn"
              >
                编辑
              </button>
              <button 
                @click="deleteUserComment(comment.id)" 
                class="delete-comment-btn"
                :disabled="isDeletingComment"
              >
                删除
              </button>
            </div>
          </div>
          
          <!-- 分页 -->
          <div v-if="commentsPagination.total_pages > 1" class="pagination">
            <button 
              @click="loadCommentsPage(commentsPagination.page - 1)"
              :disabled="commentsPagination.page <= 1"
              class="pagination-btn"
            >
              上一页
            </button>
            
            <span class="pagination-info">
              第 {{ commentsPagination.page }} 页，共 {{ commentsPagination.total_pages }} 页
            </span>
            
            <button 
              @click="loadCommentsPage(commentsPagination.page + 1)"
              :disabled="commentsPagination.page >= commentsPagination.total_pages"
              class="pagination-btn"
            >
              下一页
            </button>
          </div>
        </div>
        
        <div v-else class="no-comments">
          <p>您还没有发表任何留言</p>
          <router-link to="/movies" class="browse-movies-btn">
            去电影库看看
          </router-link>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useMoviesStore } from '@/stores/movies'
import { useRatingsStore } from '@/stores/ratings'
import { commentAPI } from '@/services/api'
import type { Rating, Comment } from '@/types'

const router = useRouter()
const authStore = useAuthStore()
const moviesStore = useMoviesStore()
const ratingsStore = useRatingsStore()

// 留言相关状态
const userComments = ref<Comment[]>([])
const isLoadingComments = ref(false)
const isDeletingComment = ref(false)
const commentsPagination = ref({
  page: 1,
  page_size: 10,
  total_pages: 1,
  count: 0
})

// 计算属性
const fullName = computed(() => {
  const user = authStore.user
  if (user?.first_name || user?.last_name) {
    return `${user.first_name || ''} ${user.last_name || ''}`.trim()
  }
  return ''
})

const userInitials = computed(() => {
  const user = authStore.user
  if (user?.first_name && user?.last_name) {
    return `${user.first_name[0]}${user.last_name[0]}`.toUpperCase()
  }
  return user?.username?.[0]?.toUpperCase() || 'U'
})

const recentRatings = computed(() => {
  return ratingsStore.ratings
    .slice()
    .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
    .slice(0, 10)
})

const ratingDistribution = computed(() => {
  const distribution = [1, 2, 3, 4, 5].map(rating => ({
    rating,
    count: ratingsStore.ratings.filter(r => r.rating === rating).length
  }))
  
  return distribution.filter(d => d.count > 0)
})

const maxGenreCount = computed(() => {
  if (!moviesStore.userStats?.favorite_genres.length) return 1
  return Math.max(...moviesStore.userStats.favorite_genres.map(g => g.count))
})

const maxDistributionCount = computed(() => {
  if (!ratingDistribution.value.length) return 1
  return Math.max(...ratingDistribution.value.map(d => d.count))
})

// 方法
const goToMovie = (movieId: number) => {
  router.push({ name: 'movie-detail', params: { id: movieId } })
}

const handleLogout = async () => {
  await authStore.logout()
  router.push({ name: 'login' })
}

const refreshRatings = async () => {
  try {
    await ratingsStore.fetchRatings()
    await moviesStore.fetchUserStats()
  } catch (error) {
    console.error('刷新评分失败:', error)
  }
}

const getGenrePercentage = (count: number) => {
  return (count / maxGenreCount.value) * 100
}

const getDistributionPercentage = (count: number) => {
  return (count / maxDistributionCount.value) * 100
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays} 天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

// 留言相关方法
const loadUserComments = async (page = 1) => {
  try {
    isLoadingComments.value = true
    
    const response = await commentAPI.getUserComments({
      page,
      page_size: commentsPagination.value.page_size
    })
    
    userComments.value = response.data.results
    commentsPagination.value = {
      page: response.data.page,
      page_size: response.data.page_size,
      total_pages: response.data.total_pages,
      count: response.data.count
    }
  } catch (error) {
    console.error('加载留言失败:', error)
  } finally {
    isLoadingComments.value = false
  }
}

const refreshComments = async () => {
  await loadUserComments(1)
}

const loadCommentsPage = (page: number) => {
  loadUserComments(page)
}

const editComment = (comment: Comment) => {
  // 跳转到电影详情页面，用户可以在那里编辑留言
  router.push({ name: 'movie-detail', params: { id: comment.movie } })
}

const deleteUserComment = async (commentId: number) => {
  if (!confirm('确定要删除这条留言吗？')) return
  
  try {
    isDeletingComment.value = true
    
    await commentAPI.deleteComment(commentId)
    
    // 重新加载当前页面的留言
    await loadUserComments(commentsPagination.value.page)
  } catch (error) {
    console.error('删除留言失败:', error)
    alert('删除留言失败，请稍后重试')
  } finally {
    isDeletingComment.value = false
  }
}

// 页面初始化
onMounted(async () => {
  try {
    await Promise.all([
      ratingsStore.fetchRatings(),
      moviesStore.fetchUserStats(),
      loadUserComments()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
  }
})
</script>

<style scoped>
.profile-view {
  min-height: 100vh;
  background-color: #f8fafc;
}

/* 导航栏样式 */
.navbar {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70px;
}

.nav-brand h2 {
  color: #667eea;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-link {
  color: #64748b;
  text-decoration: none;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.nav-link:hover,
.nav-link.active {
  color: #667eea;
  background-color: #f1f5f9;
}

.nav-user {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  color: #475569;
  font-weight: 500;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #dc2626;
}

/* 主要内容样式 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
  display: flex;
  flex-direction: column;
  gap: 40px;
}

/* 用户信息卡片 */
.user-info-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 40px;
  display: flex;
  align-items: center;
  gap: 30px;
}

.user-avatar {
  flex-shrink: 0;
}

.avatar-circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  font-weight: 700;
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.user-name-title {
  color: #1e293b;
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 10px 0;
}

.user-email {
  color: #64748b;
  font-size: 16px;
  margin: 0 0 5px 0;
}

.user-username {
  color: #94a3b8;
  font-size: 14px;
  margin: 0;
}

/* 统计信息 */
.stats-section h2,
.favorite-genres-section h2,
.recent-ratings-section h2,
.rating-distribution-section h2 {
  color: #1e293b;
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 20px 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f1f5f9;
  border-radius: 12px;
}

.stat-content h3 {
  color: #667eea;
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 5px 0;
}

.stat-content p {
  color: #64748b;
  margin: 0;
  font-weight: 500;
}

/* 喜爱类型图表 */
.favorite-genres-section,
.rating-distribution-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.genres-chart,
.distribution-chart {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.genre-bar,
.distribution-bar {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.genre-info,
.distribution-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.genre-name,
.distribution-rating {
  color: #1e293b;
  font-weight: 500;
}

.genre-count,
.distribution-count {
  color: #64748b;
  font-size: 14px;
}

.genre-progress,
.distribution-progress {
  height: 8px;
  background-color: #e2e8f0;
  border-radius: 4px;
  overflow: hidden;
}

.genre-progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
}

.distribution-progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #10b981 0%, #059669 100%);
  transition: width 0.3s ease;
}

/* 最近评分 */
.recent-ratings-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.refresh-btn {
  padding: 8px 16px;
  background-color: #64748b;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.refresh-btn:hover {
  background-color: #475569;
}

.ratings-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.rating-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.rating-item:hover {
  background-color: #f1f5f9;
  transform: translateX(5px);
}

.rating-movie-title {
  color: #1e293b;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 5px 0;
}

.rating-timestamp {
  color: #64748b;
  font-size: 14px;
  margin: 0;
}

.rating-score {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 5px;
}

.stars {
  display: flex;
  gap: 2px;
}

.star {
  color: #e2e8f0;
  font-size: 18px;
  transition: color 0.3s ease;
}

.star.filled {
  color: #f59e0b;
}

.rating-number {
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
}

/* 加载和空状态 */
.loading {
  text-align: center;
  padding: 40px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.no-ratings {
  text-align: center;
  padding: 40px;
}

.no-ratings p {
  color: #64748b;
  margin-bottom: 20px;
  font-size: 16px;
}

.browse-movies-btn {
  display: inline-block;
  padding: 12px 24px;
  background-color: #667eea;
  color: white;
  text-decoration: none;
  border-radius: 8px;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.browse-movies-btn:hover {
  background-color: #5a67d8;
}

/* 用户留言样式 */
.user-comments-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
  border-left: 4px solid #667eea;
  transition: all 0.3s ease;
}

.comment-item:hover {
  background: #f1f5f9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.movie-title {
  color: #667eea;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  cursor: pointer;
  transition: color 0.3s ease;
}

.movie-title:hover {
  color: #5a67d8;
  text-decoration: underline;
}

.comment-date {
  color: #64748b;
  font-size: 14px;
}

.comment-content {
  margin-bottom: 15px;
}

.comment-content p {
  color: #475569;
  line-height: 1.6;
  margin: 0;
}

.comment-actions {
  display: flex;
  gap: 10px;
}

.view-movie-btn,
.edit-comment-btn,
.delete-comment-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.view-movie-btn {
  background-color: #667eea;
  color: white;
}

.view-movie-btn:hover {
  background-color: #5a67d8;
}

.edit-comment-btn {
  background-color: #f59e0b;
  color: white;
}

.edit-comment-btn:hover {
  background-color: #d97706;
}

.delete-comment-btn {
  background-color: #ef4444;
  color: white;
}

.delete-comment-btn:hover:not(:disabled) {
  background-color: #dc2626;
}

.delete-comment-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.no-comments {
  text-align: center;
  padding: 40px 20px;
  color: #64748b;
}

.no-comments p {
  margin-bottom: 20px;
  font-size: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

.pagination-btn {
  padding: 8px 16px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #5a67d8;
}

.pagination-btn:disabled {
  background-color: #cbd5e1;
  cursor: not-allowed;
}

.pagination-info {
  color: #64748b;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-container {
    flex-direction: column;
    height: auto;
    padding: 15px 20px;
  }
  
  .nav-menu {
    margin: 15px 0;
  }
  
  .user-info-card {
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }
  
  .user-name-title {
    font-size: 24px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .rating-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .rating-score {
    align-items: flex-start;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .comment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .comment-actions {
    flex-wrap: wrap;
  }
  
  .pagination {
    flex-direction: column;
    gap: 15px;
  }
}
</style>